﻿using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System;
using System.Linq;
using System.Collections.Generic;

namespace SimpleTaskSystem
{
    [CustomEditor(typeof(TaskManager))]
    public class TaskManagerInspector : Editor
    {
        private ReorderableList taskList;

        private void OnEnable()
        {
            taskList = new ReorderableList(serializedObject, serializedObject.FindProperty("tasks"), true, true, true, true);
            taskList.elementHeight = EditorGUIUtility.singleLineHeight * 4;
            taskList.drawElementCallback = DrawNameElement;
            taskList.elementHeightCallback = DrawHeight;
            taskList.drawHeaderCallback = (Rect rect) =>
            {
                GUI.Label(rect, "任务列表");
            };
        }

        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            taskList.DoLayoutList();
            serializedObject.ApplyModifiedProperties();
        }

        private void DrawNameElement(Rect rect, int index, bool selected, bool focused)
        {
            //绘制分割线
            Rect lineRect = rect;
            lineRect.x -= 18;
            lineRect.width += 22;
            lineRect.height = 4;
            Color c = new Color(.6f, .23f, .05f, 1f);
            EditorGUI.DrawRect(lineRect,c);


            var element = taskList.serializedProperty.GetArrayElementAtIndex(index);
            rect.y += 4;
            EditorGUI.PropertyField(new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight * 2, rect.width, EditorGUIUtility.singleLineHeight), element);

            //绘制标题
            GUIStyle gs = new GUIStyle();
            c.r += 0.2f;
            c.g += 0.1f;
            gs.normal.textColor = c;
            gs.fontSize = 25;
            gs.fontStyle = FontStyle.Bold;
            EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), index + "、" + element.FindPropertyRelative("taskName").stringValue, gs);
        }

        float DrawHeight(int index)
        {
            var element = taskList.serializedProperty.GetArrayElementAtIndex(index);
            float h = EditorGUI.GetPropertyHeight(element);
            return h + 8;
        }
    }
}